<!-- src/components/CompanyCard.vue -->
<template>
    <div class="cards-container">
        <div class="card-top">
            <div class="card_top_title">
                <div>{{ company.fullName }}</div>
                <div class="create_time">创建时间：{{ company.createAt.split("T")[0] }}

                    {{ company.createAt.split("T")[1] }}
                </div>
            </div>
            <div class="id-tag">
                <van-tag plain type="primary">ID: {{ company.id }}</van-tag>
            </div>

        </div>

        <van-cell-group :border="false">
            <van-cell class="nav-card" @click="viewDetails">
                <template #title>
                    <div class="card-content">
                        <div class="card-left">
                            <div class="card-icon company-info-icon">
                                <van-icon name="newspaper" size="35" />
                            </div>
                        </div>
                        <div class="card-text-container">
                            <!-- <div class="card-title">
                                {{ company.fullName }}

                            </div> -->

                            <div class="company-desc">
                                <div class="card-desc-item">
                                    <van-icon name="shop-o" />
                                    <span>主营业务: {{ company.business }}</span>
                                </div>
                                <div class="card-desc-item">
                                    <van-icon name="balance-o" />
                                    <span>年度营收: {{ company.lastRevenue }}万元</span>
                                </div>
                                <div class="card-desc-item">
                                    <van-icon name="friends-o" />
                                    <span>总人数: {{ company.totalCount }}人</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
                <template #right-icon>

                </template>
            </van-cell>
        </van-cell-group>
        <!-- 步骤条 -->
        <VerticalSteps :currentStep="checkCompanyStatus()" />

        <!-- 操作栏 -->
        <div class="action-bar">
            <van-button class="action-button" size="small" @click="exportExcel()">导出表格</van-button>
            <van-button class="action-button" size="small" @click="handelUpload()">导入数据</van-button>
            <van-button class="action-button" size="small" @click="handleViewDetails()">查看详情</van-button>
            <van-button class="action-button" size="small">短信通知</van-button>
        </div>
        <!-- 圆角弹窗（底部） -->
        <van-popup v-model:show="showBottom" round position="bottom" :style="{ height: '20%' }">
            <div class="upload-popup">
                <div class="popup-header">
                    <span>导入数据</span>
                    <van-icon name="close" @click="showBottom = false" />
                </div>
                <div class="upload-options">
                    <van-uploader :after-read="handleImageUpload" accept="image/*">
                        <div class="upload-option" @click="selectImageUpload">
                            <van-icon name="photo" size="30" color="#1989fa" />
                            <span>二维码上传</span>
                        </div>
                    </van-uploader>
                    <van-uploader :after-read="handlePdfUpload" accept=".pdf">
                        <div class="upload-option" @click="selectPdfUpload">
                            <van-icon name="orders-o" size="30" color="#1989fa" />
                            <span>PDF上传</span>
                        </div>
                    </van-uploader>

                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref, onMounted } from 'vue'
import VerticalSteps from './VerticalSteps.vue';
import { showToast } from 'vant';
import { exportEmployeeExcel } from '../../api/exportEmployeeExcel';
import type { UploaderFileListItem } from 'vant';
import { uploadImage, uploadPdf } from '../../api/upload';
import { addFilePath, getFilePathById, uploadFilePath } from '../../api/uploadFliePath';
// 定义组件属性
const props = defineProps<{
    company: {
        id: number
        fullName: string
        business: string
        lastRevenue: string
        totalCount: number
        [key: string]: any // 其他可能的属性
    }
}>()

const showBottom = ref(false)


// 定义事件
const emit = defineEmits<{
    (e: 'view-details', id: number): void
}>()

// 查看详情处理函数
const viewDetails = () => {
    emit('view-details', props.company.id)
}

/**
 * 判断字段是否非空
 * @param fieldValue 
 */
const isFieldNotEmpty = (fieldValue: any) => {
    return fieldValue !== null &&
        fieldValue !== undefined &&
        fieldValue !== '' &&
        !(Array.isArray(fieldValue) && fieldValue.length === 0);
}


// 使用示例
const checkCompanyStatus = () => {
    switch (true) {
        case isFieldNotEmpty(props.company.currentMenber):
            return 3;
        case isFieldNotEmpty(props.company.orgJson):
            return 2;
        case isFieldNotEmpty(props.company.business):
            return 1;
        default:
            return 0;
    }
}
// 处理数据，添加 departmentName 字段
const processDataList = (dataList: any[]) => {
    return dataList.map((item, index) => {
        // 获取 department 字段中最后一个斜杠后的内容作为 departmentName
        const departmentPath = item.department || '';
        const departmentParts = departmentPath.split('/');
        const departmentName = departmentParts[departmentParts.length - 1];

        return {
            index: index + 1,
            ...item,
            departmentName: departmentName
        };
    });
};

const exportExcel = async () => {
    //    1.校验步骤状态 判断提示
    const stepNumber = checkCompanyStatus()
    if (stepNumber < 3) {
        showToast('请完善成员信息后再导出！')
        return
    }
    // 2.构造表格数据
    const excelData = props.company.currentMenber
    const dataList = JSON.parse(excelData)
    // 3.处理数据，添加 departmentName 字段
    const processedData = processDataList(dataList);
    // console.log("处理后的数据:", processedData)
    await exportEmployeeExcel(processedData, `${props.company.fullName}_员工信息.xlsx`)
}

const handelUpload = () => {
    showBottom.value = true
}

const selectImageUpload = () => {
    // 实现图片上传逻辑
    showBottom.value = false;
    // 可以调用文件选择API或者跳转到相应页面
}

const selectPdfUpload = () => {
    // 实现PDF上传逻辑
    showBottom.value = false;
    // 可以调用文件选择API或者跳转到相应页面
}

const handelUploadPath = async (paramsType: any, path: any) => {
    // 1.根据id 获取文件保存路径
    const response = await getFilePathById(props.company.id).catch(err => {
        console.log("获取失败", err);
    });
    console.log("获取成功", response);
    if (response) {
        // 1.查询成功修改文件保存路径
        const data = response.data;
        if (paramsType == "pdf") {
            data.pdf = path
        } else {
            data.image = path
        }
        await uploadFilePath(data).catch(err => {
            console.log("修改失败", err);
        });
    } else {
        // 2.查询失败 新增文件保存路径
        const data = {
            id: props.company.id,
            image: "",
            pdf: ""
        }
        if (paramsType == "pdf") {
            data.pdf = path
        } else {
            data.image = path
        }
        await addFilePath(data).catch(err => {
            console.log("新增失败", err);
        })
    }
}




const handleImageUpload = async (items: UploaderFileListItem | UploaderFileListItem[]) => {
    // 如果是多个文件，取第一个处理
    const fileItem = Array.isArray(items) ? items[0] : items;

    // 增加对 fileItem 和 fileItem.file 的安全检查
    if (fileItem && fileItem.file) {
        try {
            showToast('正在上传图片...');
            const response = await uploadImage(fileItem.file);
            showToast('图片上传成功');
            console.log('图片上传成功:', response.data);
            // 可以在这里处理上传成功后的逻辑，比如更新页面状态等
            handelUploadPath("image", response.data)
        } catch (error) {
            showToast('图片上传失败');
            console.error('图片上传失败:', error);
        }
    } else {
        showToast('文件读取失败');
    }
}
// PDF上传处理函数
const handlePdfUpload = async (items: UploaderFileListItem | UploaderFileListItem[]) => {
    // 如果是多个文件，取第一个处理
    const fileItem = Array.isArray(items) ? items[0] : items;

    // 增加对 fileItem 和 fileItem.file 的安全检查
    if (fileItem && fileItem.file) {
        try {
            showToast('正在上传PDF...');
            const response = await uploadPdf(fileItem.file);
            showToast('PDF上传成功');
            console.log('PDF上传成功:', response.data);
            // 可以在这里处理上传成功后的逻辑
            handelUploadPath("pdf", response.data)
        } catch (error) {
            showToast('PDF上传失败');
            console.error('PDF上传失败:', error);
        }
    } else {
        showToast('文件读取失败');
    }
}

//路由跳转
import { useRouter } from 'vue-router'
const router = useRouter()
//跳转详情页的方法
const handleViewDetails = () => {
    console.log('查看企业详情:', props.company.id)
    // 在这里添加跳转到详情页的逻辑
    router.push({ path: '/detailPage', query: { id: props.company.id } })
}

onMounted(async () => {



})
</script>

<style scoped lang="scss">
.cards-container {
    width: 90vw;
    margin-top: 2vh;
    background: white;
    border-radius: 10px;
    border: 1px solid #e0e0e0;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    padding: 5px;
}

.nav-card {
    margin: 0;
}

.nav-card:not(:last-child) {
    border-bottom: 1px solid #f0f0f0;
}

.card-content {
    display: flex;
    align-items: center;
    padding: 15px 0;
}

.card-icon {
    width: 65px;
    height: 65px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    flex-shrink: 0;
}

.company-info-icon {
    background-color: #e1f5fe;
    color: #039be5;
}

.card-text-container {
    flex: 1;
}

.card-title {
    font-size: 20px;
    color: #333;
    font-weight: 500;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}



.company-desc {
    margin-top: 4px;
}

.card-desc-item {
    display: flex;
    align-items: baseline;
    margin-bottom: 4px;
    font-size: 14px;
    color: #666;
}

.card-desc-item:last-child {
    margin-bottom: 0;
}

.card-desc-item :deep(.van-icon) {
    margin-right: 5px;
    font-size: 14px;
}

.detail-button {
    margin-right: 10px;
}

.action-bar {
    display: flex;
    justify-content: space-evenly;
    padding: 10px 15px;
    /* 添加顶部边框线 */
    border-top: 1px solid #f0f0f0;

    gap: 10px;
}

.action-button {
    font-size: 12px;
}

.upload-options {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: calc(100% - 60px);
}

.upload-option {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    padding: 2vh;
}

.upload-option .van-icon {
    font-size: clamp(16px, 3vh, 24px) !important;
    margin-bottom: 0.5vh;
}

.upload-option span {
    font-size: clamp(12px, 2vh, 16px);
    text-align: center;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: clamp(14px, 2.5vh, 20px);
    font-weight: 500;
    margin-bottom: 2vh;
    padding-bottom: 1vh;
    border-bottom: 1px solid #f0f0f0;
}

.upload-popup {
    height: 100%;
    padding: 2vh clamp(15px, 2vw, 25px);
    box-sizing: border-box;
}

.card-left {
    display: flex;
    flex-direction: column;
    align-items: start;
    justify-self: center;
    text-align: center;
    margin-right: 2vw;
}

.card-top {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 0.5vh 0;
    padding-left: 2vw;
    align-items: baseline;

    .card_top_title {
        display: flex;
        flex-direction: column;
        align-items: start;
        justify-self: start;
        font-size: clamp(16px, 2vh, 20px);
        text-align: left;
        word-break: break-all;
        /* 强制换行 */
        white-space: normal;
        /* 允许换行 */
    }

    .create_time {
        font-size: clamp(12px, 1.5vh, 16px);
        color: #999;
    }

    .id-tag {
        text-align: left;
        font-size: 10px;
        margin-right: 5vw;
        margin-left: 5vw;

    }
}

:deep(.van-cell-group) {
    border-radius: 75px;

    background-color: transparent;
}
</style>